package com.image.upload;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.stream.ImageInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class Upload extends ActionSupport {
	private File image;
	private File cutImage;
	private File Filedata; // 上传的文件
	private String FiledataFileName; // 文件名称
	private String FiledataContentType;
    private String imagename;
	private String savePath;
	private int x;
	private int y;
	private int w;
	private int h;
	private String srcImage;
	private String filePath;

	public String test() {
		System.out.println("action - test");
		return "success"  ;
	}

	public String ajax(String content, String type) {
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType(type + ";charset=UTF-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			response.getWriter().write(content);
			response.getWriter().flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 根据字符串输出JSON，返回null
	public String ajaxJson(String jsonString) {
		return ajax(jsonString, "text/html");
	}

	public String uploadimage() {
		FileOutputStream fos = null;
		FileInputStream fis = null;
		JSONObject jsonObject = new JSONObject();
		try {
			filePath = ServletActionContext.getServletContext().getRealPath("")+"/photo/";
			File pathDir = new File(filePath);
			if (!pathDir.exists())
				pathDir.mkdirs();
			String imageFile = filePath + FiledataFileName;
			fos = new FileOutputStream(imageFile);
			fis = new FileInputStream(Filedata);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}

			jsonObject.put("filePath", imageFile);
			jsonObject.put("name",FiledataFileName);
			System.out.println("文件名:"+FiledataFileName);
		} catch (Exception e) {
			System.out.println("文件上传失败");
			e.printStackTrace();
		} finally {
			close(fos, fis);
		}
		return ajaxJson(JSONObject.fromObject(jsonObject).toString());
	}

	public String download() {
		HttpServletResponse response = ServletActionContext.getResponse();
		FileOutputStream fos = null;
		FileInputStream fis = null;
		ServletOutputStream sos = null;
		try {
			if (filePath != null)
				image = new File(filePath);
			if (image.exists()) {
				fis = new FileInputStream(image);

				// 创建一个长度的字节数组bt
				byte[] bt = new byte[fis.available()];
				// 将文件转换成字节保存到字节数组bt中
				fis.read(bt);
				/** 服务器往客户端写： */
				response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");
				String fileName = java.net.URLEncoder.encode(image.getName(),
						"UTF-8");
				response.setHeader(
						"Content-Disposition",
						"attachment; filename="
								+ new String(fileName.getBytes("UTF-8"), "GBK"));
				// 设置下载长度
				response.setContentLength(bt.length);
				// 获取写入流，
				sos = response.getOutputStream();
				// 向客户端写数据
				sos.write(bt);

			}
		} catch (Exception e) {
			// TODO: handle exception
		} finally {
			close(fos, fis);
			// sos.close();
		}

		return null;
	}

	public String imageCut() {
		/*
		 * 获取参数 x,y,w,h,bigImage
		 */
		int x = Integer.valueOf(getX());
		int y = Integer.valueOf(getY());
		int w = Integer.valueOf(getW());
		int h = Integer.valueOf(getH());		
		filePath = ServletActionContext.getServletContext().getRealPath("")+"/photo/"+imagename;		
		ImageCut imageCut = new ImageCut();
		imageCut.cutImage(imagename,filePath, x, y, w, h);
		String subPath=ServletActionContext.getServletContext().getRealPath("")+"/cutImage/"+imagename;
		JSONObject jsonObject=new JSONObject();
		jsonObject.put("filePath",subPath);
		return ajaxJson(JSONObject.fromObject(jsonObject).toString());
	}

	private void close(FileOutputStream fos, FileInputStream fis) {
		if (fis != null) {
			try {
				fis.close();
			} catch (IOException e) {
				System.out.println("FileInputStream关闭失败");
				e.printStackTrace();
			}
		}
		if (fos != null) {
			try {
				fos.close();
			} catch (IOException e) {
				System.out.println("FileOutputStream关闭失败");
				e.printStackTrace();
			}
		}
	}

	public File getFiledata() {
		return Filedata;
	}

	public void setFiledata(File filedata) {
		Filedata = filedata;
	}

	public String getFiledataFileName() {
		return FiledataFileName;
	}

	public void setFiledataFileName(String filedataFileName) {
		FiledataFileName = filedataFileName;
	}

	public String getFiledataContentType() {
		return FiledataContentType;
	}

	public void setFiledataContentType(String filedataContentType) {
		FiledataContentType = filedataContentType;
	}

	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath(savePath);
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public int getW() {
		return w;
	}

	public void setW(int w) {
		this.w = w;
	}

	public int getH() {
		return h;
	}

	public void setH(int h) {
		this.h = h;
	}

	public String getSrcImage() {
		return srcImage;
	}

	public void setSrcImage(String srcImage) {
		this.srcImage = srcImage;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public File getCutImage() {
		return cutImage;
	}

	public void setCutImage(File cutImage) {
		this.cutImage = cutImage;
	}

	public String getImagename() {
		return imagename;
	}

	public void setImagename(String imagename) {
		this.imagename = imagename;
	}
    
}
